const API = require('../utils/api')
// 先判断用户是否登录
const checkWxLoginStatus = function () {
    return new Promise((resolve, reject) => {
        wx.checkSession({
            success() {
                resolve(true)
            },
            fail() {
                resolve(false)
            }
        })
    })
}
const hasUserIsLogined = async function () {
    const token = wx.getStorageSync('token')
    if (!token) {
        return false;
    }
    const res = await API.checkTokenApi(token)
    console.log(res);
    const wxStatus = await checkWxLoginStatus()

    if (!wxStatus) {
        wx.removeStorageSync('token')
        return false

    }
    return true

}

const autoRegAndLogin = function () {
    wx.login({
        success: async function (res) {

            console.log('code:', res.code)
            const res2 = await API.autoRegAndLoginApi(res.code)
            console.log('自动登录和注册res：', res2)
            wx.setStorageSync('token', res2.token)

            wx.setStorageSync('uid', res2.uid)

        },
        fail(error) {
            console.log('登录失败' + error)
        }
    })
}
module.exports = {
    hasUserIsLogined,
    autoRegAndLogin
}